package com.madai.chatroom.activity.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.os.Message
import android.widget.Button
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.madai.chatroom.activity.MsgAdapter
import com.madai.chatroom.R
import com.madai.chatroom.activity.ChatMsg
import java.io.*
import java.net.Socket
import java.util.*

class ChatActivity : AppCompatActivity(), View.OnClickListener {
    private val chatMsgList: MutableList<ChatMsg> = ArrayList()
    private val host: String = "10.90.28.194"
    private val port: Int = 8080
    private var adapter: MsgAdapter? = null
    private var socketRun: Socket? = null
    private var dis: BufferedReader? = null
    private var dos: PrintWriter? = null
    private var isRunning = false
    private var recyclerViewMsg: RecyclerView? = null
    private var btnSend: Button? = null
    private var editMsg: EditText? = null

    private val socketHandler: Handler = Handler {
        if (it.obj != null) {
            val message = ChatMsg(it.obj.toString(), ChatMsg.TYPE_RECEIVED)
            chatMsgList.add(message)
            adapter?.notifyItemInserted(chatMsgList.size - 1)
            recyclerViewMsg!!.scrollToPosition(chatMsgList.size - 1)
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)
        recyclerViewMsg = findViewById(R.id.recyclerViewMsg_chatRoom)
        btnSend = findViewById(R.id.btnSend_chatRoom)
        editMsg = findViewById(R.id.editMsg_chatRoom)
        btnSend!!.setOnClickListener(this)
        runOnUiThread {
            recyclerViewMsg!!.layoutManager = LinearLayoutManager(this)
            recyclerViewMsg!!.adapter = MsgAdapter(chatMsgList)
        }
        Thread {
            try {
                socketRun = Socket(host, port)
                if (socketRun != null) {
                    isRunning = true
                    dis = BufferedReader(InputStreamReader(socketRun!!.getInputStream(), "UTF-8"))
                    dos = PrintWriter(
                        BufferedWriter(
                            OutputStreamWriter(
                                socketRun!!.getOutputStream()
                            )
                        ), true
                    )
                    Thread(MyReceive(), "接收线程").start()
                }
            } catch (e: Exception) {
                isRunning = false
                e.printStackTrace()
                Looper.prepare()
                Looper.loop()
                try {
                    socketRun?.close()
                } catch (e1: IOException) {
                    e1.printStackTrace()
                }
                finish()
            }
        }.start()
    }

    override fun onClick(view: View) {
        if (view.id == R.id.btnSend_chatRoom) {
            var content = editMsg!!.text.toString()
            val sb = StringBuilder()
            sb.append(content)
            content = sb.toString()
            if ("" != content) {
                val message = ChatMsg(content, ChatMsg.TYPE_SENT)
                chatMsgList.add(message)
                adapter?.notifyItemInserted(chatMsgList.size - 1)
                recyclerViewMsg!!.scrollToPosition(chatMsgList.size - 1)
                try {
                    dos?.println(content)
                    editMsg!!.setText("")
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            sb.delete(0, sb.length)
        }
    }

    internal inner class MyReceive : Runnable {
        override fun run() {
            var recMsg = ""
            while (isRunning) {
                try {
                    if (dis?.readLine().also { recMsg = it.toString() } != null) {
                        val msg = Message()
                        msg.obj = recMsg
                        socketHandler.sendMessage(msg)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }
}